package com.bicon.life.core.base.common.controller;

import com.bicon.life.core.base.common.BusinessException;
import com.bicon.life.core.base.common.Constants;
import com.bicon.life.core.base.common.entity.BaseResult;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 基础Controller
 * @author tandk
 * @date 2017/7/26 0026 下午 16:14
 */
public abstract class BaseController {

    /**
     * 获取userId
     * @return
     */
    public String getUserId(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object o = request.getAttribute("userId");
        if(o == null){
            throw new BusinessException(Constants.RESPONSE_CODE_300, Constants.RESPONSE_MESSAGE_300);
        }
        return (String) o;
    }

    private BaseResult baseResult;

    public BaseResult sendResult200() {
        return baseResult = new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    public BaseResult sendResult200(Object data) {
        return baseResult = new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, data);
    }

    public BaseResult sendResult400() {
        return baseResult = new BaseResult(Constants.RESPONSE_CODE_400, Constants.RESPONSE_MESSAGE_400);
    }

    public BaseResult sendResult400(Object data) {
        return baseResult = new BaseResult(Constants.RESPONSE_CODE_400, Constants.RESPONSE_MESSAGE_400, data);
    }

    public BaseResult sendResult500() {
        return baseResult = new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
    }

    public BaseResult sendResult500(Object data) {
        return baseResult = new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500, data);
    }

    public BaseResult sendResult(int code, String message) {
        return baseResult = new BaseResult(code, message);
    }

    public BaseResult sendResult(int code, String message, Object data) {
        return baseResult = new BaseResult(code, message, data);
    }
    public BaseResult sendResult(int code, String message, Object data,String mark) {
        if(data==null){
            if(mark.equals(Constants.RESULT_JSON_DATA_OBJECT)){
                data=new JsonObject();
            }else if(mark.equals(Constants.RESULT_JSON_DATA_COLLECTION)){
                data=new JsonArray();
            }
        }
        return baseResult = new BaseResult(code, message, data);
    }
    public BaseResult getBaseResult() {
        return baseResult;
    }

    public void setBaseResult(BaseResult baseResult) {
        this.baseResult = baseResult;
    }

}